package aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock {

    class MyAbstractQueuedSynchronizer extends AbstractQueuedSynchronizer {

        /**
         * 尝试获取锁
         *
         * @param arg 参数
         * @return boolean
         */
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        /**
         * 尝试释放锁
         *
         * @param arg 参数
         * @return boolean
         */
        @Override
        protected boolean tryRelease(int arg) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        /**
         * 是否持有锁
         *
         * @return boolean
         */
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        /**
         * 获取Condition
         *
         * @return {@link Condition}
         */
        private Condition newCondition() {
            return new ConditionObject();
        }

    }

    private MyAbstractQueuedSynchronizer abstractQueuedSynchronizer = new MyAbstractQueuedSynchronizer();

    /**
     * 加锁
     */
    @Override
    public void lock() {
        abstractQueuedSynchronizer.acquire(1);
    }

    /**
     * 可中断的锁
     *
     * @throws InterruptedException 中断异常
     */
    @Override
    public void lockInterruptibly() throws InterruptedException {
        abstractQueuedSynchronizer.acquireInterruptibly(1);

    }

    /**
     * 尝试获取锁
     *
     * @return boolean
     */
    @Override
    public boolean tryLock() {
        return abstractQueuedSynchronizer.tryAcquire(1);
    }

    /**
     * 尝试超时获取锁
     *
     * @param time 时间
     * @param unit 单位
     * @return boolean
     * @throws InterruptedException 中断异常
     */
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return abstractQueuedSynchronizer.tryAcquireNanos(1, unit.toNanos(time));
    }

    /**
     * 解锁
     */
    @Override
    public void unlock() {
        abstractQueuedSynchronizer.release(0);
    }

    /**
     * 新条件
     *
     * @return {@link Condition}
     */
    @Override
    public Condition newCondition() {
        return abstractQueuedSynchronizer.newCondition();
    }

}
